﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace BrnMall.Core.Http
{
    public class HttpRequest
    {
        public string Method { get; set; }
        public string ContentType { get; set; }
        public HttpRequest()
        {
            Method = "GET";
            ContentType = "application/x-www-form-urlencoded";
        }

        public bool DownLoadImage(string url, string savePath)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = Method;
            request.ContentType = ContentType;
            var response = (HttpWebResponse)request.GetResponse();
            var resStream = response.GetResponseStream();
            if (resStream == null) return false;

            DirectoryInfo dInfo = new DirectoryInfo(savePath);
            string dirPath = dInfo.FullName.Substring(0, dInfo.FullName.LastIndexOf("\\"));
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);

            using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                byte[] buff = new byte[512];
                int c = 0; //实际读取的字节数
                while ((c = resStream.Read(buff, 0, buff.Length)) > 0)
                {
                    fs.Write(buff, 0, c);
                }
            }
            return true;
        }
    }
}
